'use client';

import React, { useState, useEffect } from 'react';
import { useRouter, useParams } from 'next/navigation';
import { 
  Card, 
  Typography, 
  Space, 
  Tag, 
  Button, 
  Descriptions, 
  Select, 
  message,
  Spin,
  Popconfirm
} from 'antd';
import { 
  ArrowLeftOutlined, 
  EditOutlined, 
  DeleteOutlined,
  UserOutlined,
  CalendarOutlined,
  ClockCircleOutlined
} from '@ant-design/icons';
import dayjs from 'dayjs';
import { Ticket, UpdateTicketRequest, ApiResponse, TicketStatus } from '@/types/ticket';
import { 
  getStatusLabel, 
  getStatusColor, 
  getPriorityLabel, 
  getPriorityColor,
  getCategoryLabel,
  getCategoryColor,
  TICKET_STATUS_OPTIONS
} from '@/utils/constants';

const { Title, Paragraph, Text } = Typography;
const { Option } = Select;

const TicketDetailPage: React.FC = () => {
  const router = useRouter();
  const params = useParams();
  const [ticket, setTicket] = useState<Ticket | null>(null);
  const [loading, setLoading] = useState(true);
  const [updating, setUpdating] = useState(false);

  const ticketId = params.id as string;

  // 获取工单详情
  const fetchTicketDetail = async () => {
    setLoading(true);
    try {
      const response = await fetch(`/api/tickets/${ticketId}`);
      const result: ApiResponse<Ticket> = await response.json();

      if (result.success) {
        setTicket(result.data);
      } else {
        message.error(result.message || '获取工单详情失败');
        router.push('/');
      }
    } catch (error) {
      console.error('获取工单详情失败:', error);
      message.error('获取工单详情失败');
      router.push('/');
    } finally {
      setLoading(false);
    }
  };

  // 更新工单状态
  const handleStatusChange = async (newStatus: TicketStatus) => {
    if (!ticket) return;

    setUpdating(true);
    try {
      const updateData: UpdateTicketRequest = {
        status: newStatus,
      };

      const response = await fetch(`/api/tickets/${ticketId}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(updateData),
      });

      const result: ApiResponse<Ticket> = await response.json();

      if (result.success) {
        setTicket(result.data);
        message.success('工单状态更新成功');
      } else {
        message.error(result.message || '更新工单状态失败');
      }
    } catch (error) {
      console.error('更新工单状态失败:', error);
      message.error('更新工单状态失败');
    } finally {
      setUpdating(false);
    }
  };

  // 删除工单
  const handleDeleteTicket = async () => {
    try {
      const response = await fetch(`/api/tickets/${ticketId}`, {
        method: 'DELETE',
      });
      const result: ApiResponse<null> = await response.json();

      if (result.success) {
        message.success('工单删除成功');
        router.push('/');
      } else {
        message.error(result.message || '删除工单失败');
      }
    } catch (error) {
      console.error('删除工单失败:', error);
      message.error('删除工单失败');
    }
  };

  const handleBack = () => {
    router.back();
  };

  useEffect(() => {
    if (ticketId) {
      fetchTicketDetail();
    }
  }, [ticketId]);

  if (loading) {
    return (
      <div className="loading-container">
        <Spin size="large" />
      </div>
    );
  }

  if (!ticket) {
    return (
      <div style={{ padding: 24, textAlign: 'center' }}>
        <Text>工单不存在</Text>
      </div>
    );
  }

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 24 }}>
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Button 
            icon={<ArrowLeftOutlined />} 
            onClick={handleBack}
            style={{ marginRight: 16 }}
          >
            返回
          </Button>
          <Title level={3} style={{ margin: 0 }}>
            工单详情
          </Title>
        </div>
        
        <div>
          <Space>
            <Popconfirm
              title="确定要删除这个工单吗？"
              onConfirm={handleDeleteTicket}
              okText="确定"
              cancelText="取消"
            >
              <Button danger icon={<DeleteOutlined />}>
                删除工单
              </Button>
            </Popconfirm>
          </Space>
        </div>
      </div>

        <Card className="detail-content">
          <div style={{ marginBottom: 24 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 16 }}>
              <Title level={3} style={{ margin: 0, flex: 1 }}>
                {ticket.title}
              </Title>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <Text strong>状态：</Text>
                <Select
                  value={ticket.status}
                  onChange={handleStatusChange}
                  loading={updating}
                  style={{ minWidth: 120 }}
                >
                  {TICKET_STATUS_OPTIONS.map(option => (
                    <Option key={option.value} value={option.value}>
                      <Tag color={option.color}>{option.label}</Tag>
                    </Option>
                  ))}
                </Select>
              </div>
            </div>

            <Space wrap style={{ marginBottom: 16 }}>
              <Tag color={getPriorityColor(ticket.priority)}>
                {getPriorityLabel(ticket.priority)}
              </Tag>
              <Tag color={getCategoryColor(ticket.category)}>
                {getCategoryLabel(ticket.category)}
              </Tag>
            </Space>

            {ticket.tags && ticket.tags.length > 0 && (
              <div style={{ marginBottom: 16 }}>
                <Text strong style={{ marginRight: 8 }}>标签：</Text>
                {ticket.tags.map((tag, index) => (
                  <Tag key={index}>{tag}</Tag>
                ))}
              </div>
            )}
          </div>

          <Descriptions bordered column={2} style={{ marginBottom: 24 }}>
            <Descriptions.Item label="报告人" span={1}>
              <Space>
                <UserOutlined />
                {ticket.reporter}
              </Space>
            </Descriptions.Item>
            
            {ticket.assignee && (
              <Descriptions.Item label="处理人" span={1}>
                <Space>
                  <UserOutlined />
                  {ticket.assignee}
                </Space>
              </Descriptions.Item>
            )}

            <Descriptions.Item label="创建时间" span={1}>
              <Space>
                <ClockCircleOutlined />
                {dayjs(ticket.createdAt).format('YYYY-MM-DD HH:mm:ss')}
              </Space>
            </Descriptions.Item>

            <Descriptions.Item label="更新时间" span={1}>
              <Space>
                <ClockCircleOutlined />
                {dayjs(ticket.updatedAt).format('YYYY-MM-DD HH:mm:ss')}
              </Space>
            </Descriptions.Item>

            {ticket.dueDate && (
              <Descriptions.Item label="截止日期" span={1}>
                <Space>
                  <CalendarOutlined />
                  <Text type={dayjs(ticket.dueDate).isBefore(dayjs()) ? 'danger' : 'secondary'}>
                    {dayjs(ticket.dueDate).format('YYYY-MM-DD')}
                    {dayjs(ticket.dueDate).isBefore(dayjs()) && ' (已逾期)'}
                  </Text>
                </Space>
              </Descriptions.Item>
            )}

            <Descriptions.Item label="工单ID" span={1}>
              <Text code>{ticket.id}</Text>
            </Descriptions.Item>
          </Descriptions>

          <div>
            <Title level={4}>详细描述</Title>
            <div style={{ 
              padding: 16, 
              backgroundColor: '#fafafa', 
              borderRadius: 6,
              border: '1px solid #d9d9d9'
            }}>
              <Paragraph style={{ margin: 0, whiteSpace: 'pre-wrap' }}>
                {ticket.description}
              </Paragraph>
            </div>
          </div>
        </Card>
    </div>
  );
};

export default TicketDetailPage; 